package cn.kxx.securty;

import cn.kxx.pojo.Permission;
import cn.kxx.pojo.Role;
import cn.kxx.pojo.User;
import cn.kxx.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class SpringSecurityUserService implements UserDetailsService {


    @Reference
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

     User user = userService.findByUsername(s);
     log.info("查询的账户信息为："+user);
     if (user==null){
         return null;
     }

        List<GrantedAuthority> list = new ArrayList<>();
        Set<Role> roles = user.getRoles();
        if (roles!=null&&roles.size()>0){

            for (Role role : roles) {
                String keyword = role.getKeyword();
                list.add(new SimpleGrantedAuthority(keyword));
                Set<Permission> permissions = role.getPermissions();
                if (permissions!=null&&permissions.size()>0){
                    for (Permission permission : permissions) {
                        list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }


        return new org.springframework.security.core.userdetails.User(s,user.getPassword(),list);
    }
}
